package org.juggers.client;

import java.util.ArrayList;
import java.util.List;

import org.juggers.domain.JugEvent;
import org.juggers.domain.Jugger;
import org.juggers.remote.JuggersService;
import org.juggers.remote.JuggersServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.HeadingElement;
import com.google.gwt.dom.client.ParagraphElement;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.SubmitButton;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Widget to display an Event
 */
public class EventWidget
    extends Composite
{
    interface MyUiBinder
        extends UiBinder<HTMLPanel, EventWidget>
    {
    }


    @UiField
    HeadingElement title;

    @UiField
    HeadingElement speakers;

    @UiField
    ParagraphElement description;

    @UiField
    SpanElement when;

    @UiField
    AnchorElement where;
    
    //@UiField
    //SpanElement participants;

    @UiField
    Button subscribe;
    
    @UiField
    Button play;

    @UiField
    Resources res;

    private JugEvent event;

    static DateTimeFormat format = DateTimeFormat.getMediumDateTimeFormat();

    private static final MyUiBinder binder = GWT.create( MyUiBinder.class );

    private static final JuggersServiceAsync juggersCalendarService = GWT.create( JuggersService.class );

    public EventWidget( JugEvent event )
    {
        this.event = event;

        initWidget( binder.createAndBindUi( this ) );

        // logo = new Image( "/images/logo/breizhjug.png" );
        title.setInnerHTML( event.getTitle() );
        speakers.setInnerHTML( formatSpeakers( event.getSpeakers() ) );
        where.setInnerHTML( event.getLocation() );
        where.setHref( "http://maps.google.fr/maps?hl=fr&q=" + URL.encode( event.getLocation() ) );
        when.setInnerHTML( format.format( event.getDateTime() ) );

        // Find a way to get the number of participants with public calendar
        // participants.setInnerHTML(String.valueOf(event.getParticipants().length - 1));
        
        // Hack
        // ça c'est vrai
        if ( Window.Location.getParameter( "play" ) == null )
        {
            play.setVisible( false );
        }
    }

    private String formatSpeakers( List<String> speakers )
    {
        boolean first = true;
        String names = "";
        for ( String speaker : speakers )
        {
            if ( !first )
            {
                names += ",";
            }
            if ( speaker.charAt( 0 ) == '@' )
            {
                speaker = speaker.substring( 1 );
            }
            names += "<span id='" + speaker + "'>" + speaker + " </span>";
            first = false;
        }
        return names;
    }

    @UiHandler( "subscribe" )
    public void handleClick( ClickEvent e )
    {
        //String url =
        //    "http://spreadsheets.google.com/a/breizhjug.org/formResponse?formkey=dGstZlhCcUlUdFNhWlVxcVF5Y0V4OFE6MA";
        new RegisterWidget( event ).show();
        
//        form.addSubmitHandler(new SubmitHandler() {
//			
//			@Override
//			public void onSubmit(SubmitEvent submitEvent) {
//				juggersCalendarService.subscribe(event.getId(), prenom.getValue(), nom.getValue(), eMail.getValue(), new AsyncCallback<Void>() {
//
//					@Override
//					public void onFailure(Throwable caught) {
//						Window.alert("Erreur lors de l'enregistrement : " + caught.getMessage());		
//					}
//
//					@Override
//					public void onSuccess(Void result) {
        // Window.alert("Vous avez été enregistré");
//						popup.hide();
//					}
//				});
//			}
//		});
    }
    
    @UiHandler( "play" )
    public void handlePlayClick( ClickEvent e )
    {
        final List<Jugger> participants = new ArrayList<Jugger>();
    	
    	final PopupPanel popup = new PopupPanel();
        popup.setAnimationEnabled(true);
        popup.setAutoHideEnabled(true);
        popup.setGlassEnabled(true);
        
        final VerticalPanel vPanel = new VerticalPanel();
        popup.add(vPanel);
        
        final VerticalPanel playPanel = new VerticalPanel();
        playPanel.setStyleName("playPanel");
        vPanel.add(playPanel);
        
        HorizontalPanel hPanel = new HorizontalPanel();
        hPanel.setWidth("300px");
        hPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
        
        Button play = new SubmitButton("Tirer au sort");
        hPanel.add(play);
        play.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				if (participants.size() > 0)
                {
                    Jugger winner = participants.remove( 0 );
                    playPanel.add( new Label( winner.getFullName() ) );
                }
				else
					Window.alert("Plus de participants!");
			}
		});
        
        Button cancel = new Button("Fermer");
        hPanel.add(cancel);
        
        cancel.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				popup.hide();
			}
		});
        
        vPanel.add( hPanel );
    	
        juggersCalendarService.getParticipants( event.getId(), new AsyncCallback<List<Jugger>>()
        {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Erreur lors du chargement des participants");
			}

			@Override
            public void onSuccess( List<Jugger> result )
            {
				participants.addAll(result);
				popup.center();
			}
		});
    }
}
